package com.ssnoodles.safe.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.ssnoodles.safe.R;
import com.ssnoodles.safe.util.StreamUtil;
import com.ssnoodles.safe.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SplashActivity extends AppCompatActivity {
    private static final String TAG = SplashActivity.class.getSimpleName();
    // 更新码
    private static final int UPDATE_VERSION = 100;

    // 进入应用程序主界面
    private static final int ENTER_HOME = 101;

    // 异常
    private static final int URL_ERRPR = 102;
    private static final int IO_ERRPR = 103;
    private static final int JSON_ERRPR = 104;

    //获取的版本信息
    private String messageText;
    private String downloadUrl;


    private TextView tv_version_name;
    // 本地版本号
    private int mLocalVersionCode;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_VERSION:
                    showUpdateDialog();
                    break;
                case ENTER_HOME:
                    centerHome();
                    break;
                case URL_ERRPR:
                    ToastUtil.show(SplashActivity.this, "url异常");
                    break;
                case IO_ERRPR:
                    ToastUtil.show(SplashActivity.this, "io异常");
                    break;
                case JSON_ERRPR:
                    ToastUtil.show(SplashActivity.this, "json异常");
                    break;
            }
        }
    };


    /**
     * 显示对话框
     */
    private void showUpdateDialog() {
        // 对话框 是在这个activity 上
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle("升级提醒");
        builder.setMessage(messageText);
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                downloadApk();
            }
        });
        // 取消对话框，跳转到主界面
        builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                centerHome();
            }
        });

        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                centerHome();
            }
        });
        builder.show();
    }

    /**
     * 下载apk
     */
    private void downloadApk() {
        // 判断sd是否看用，是否挂上
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            String path = Environment.getExternalStorageDirectory() + File.separator + "mobilesafe.apk";
            RequestParams params = new RequestParams(downloadUrl);
            params.setAutoResume(true);
            params.setSaveFilePath(path);
            x.http().get(params, new Callback.ProgressCallback<File>() {
                @Override
                public void onWaiting() {
                    Log.d(TAG, "onWaiting");
                }

                @Override
                public void onStarted() {
                    Log.d(TAG, "onStarted");
                }

                @Override
                public void onLoading(long total, long current, boolean isDownloading) {
                    Log.d(TAG, "下载中，总： "+ total + "当前： " + current);
                }

                @Override
                public void onSuccess(File result) {
                    installApk(result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.d(TAG, "下载失败：" + ex.getMessage());
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    Log.d(TAG, "onCancelled");
                }

                @Override
                public void onFinished() {
                    Log.d(TAG, "onFinished");
                }
            });
        }
    }

    /**
     * 安装apk
     *
     * 1.注明包名一致
     * 2.签名一致
     */
    private void installApk(File result) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
        startActivity(intent);
        startActivityForResult(intent, 0);
    }

    /**
     * 开启一个activity 后执行的
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        centerHome();
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 进入应用程序主界面
     */
    private void centerHome() {
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);

        // 开启新的界面后，欢迎界面只可见一次。
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        x.view().inject(this);

        //初始化ui
        initUI();
        //初始化数据
        initData();
    }

    private void initData() {
        // 1 显示版本名称
        tv_version_name.setText(getVersionName());
        // 2 检测是否有最新的版本
        mLocalVersionCode = getVersionCode();
        // json 1. 版本号， 信息， 下载地址
        checkVersion();
    }

    private void checkVersion() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message message = Message.obtain();
                long startTime = System.currentTimeMillis();
                try {
                    URL url = new URL("http://172.16.11.168:8080/version.json");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setConnectTimeout(2000);
                    urlConnection.setReadTimeout(2000);
                    if (urlConnection.getResponseCode() == 200) {
                        InputStream inputStream = urlConnection.getInputStream();
                        String json = StreamUtil.streamToString(inputStream);

                        JSONObject jsonObject = new JSONObject(json);
                        String versionName = jsonObject.getString("versionName");
                        String versionCode = jsonObject.getString("versionCode");
                        messageText = jsonObject.getString("message");
                        downloadUrl = jsonObject.getString("url");

                        Log.d(TAG, versionName);
                        Log.d(TAG, String.valueOf(versionCode));
                        Log.d(TAG, messageText);
                        Log.d(TAG, downloadUrl);

                        if (mLocalVersionCode < Double.parseDouble(versionCode)) {
                            // 提示更新 ,子线程不能 操作UI
                            message.what = UPDATE_VERSION;
                        } else {
                            //进入主界面
                            message.what = ENTER_HOME;
                        }

                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    message.what = URL_ERRPR;
                } catch (IOException e) {
                    e.printStackTrace();
                    message.what = IO_ERRPR;
                } catch (JSONException e) {
                    e.printStackTrace();
                    message.what = JSON_ERRPR;
                }finally {
                    // 代码太快，欢迎界面看不到，强制等待4秒
                    long endTime = System.currentTimeMillis();
                    if (endTime - startTime < 4000) {
                        try {
                            Thread.sleep(4000 - (endTime - startTime));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // 发送消息
                    mHandler.sendMessage(message);
                }
            }
        }).start();
    }

    private int getVersionCode() {
        PackageManager packageManager = getPackageManager();
        // 传0 ，基本信息
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void initUI() {
        tv_version_name = (TextView) findViewById(R.id.tv_version_name);
    }

    private String getVersionName() {
        PackageManager packageManager = getPackageManager();
        // 传0 ，基本信息
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
